// 部门台账填写
<template>
    <div class="box">
        <!-- 头部筛选 -->
        <span class="el-input">
            年份：
            <el-select v-model="yearNumber" @change="apply" style="margin-right: 30px">
                <el-option v-for="year in yearOptions" :key="year.value" :label="year.label"
                    :value="year.value"></el-option>
            </el-select>
            工作台账：
            <el-select v-model="work_standingbook" placeholder="请选择" style="margin-top: 20px; margin-right: 30px">
                <el-option v-for="work in WorkingbookOptions" :key="work.value" :label="work.label"
                    :value="work.value"></el-option>
            </el-select>
            进展状态：
            <el-select v-model="Working_status" placeholder="请选择" style="margin-top: 20px; margin-right: 30px">
                <el-option v-for="works in Working_statusOptions" :key="works.value" :label="works.label"
                    :value="works.value"></el-option>
            </el-select>
            成绩申诉状态：
            <el-select v-model="statet" @change="apply">
                <el-option v-for="status in statusOptions" :key="status.value" :label="status.label"
                    :value="status.value"></el-option>
            </el-select>
        </span>

        <!-- 按钮 -->
        <div class="an">
            <el-button type="success" size="mini" icon="el-icon-plus" plain style="margin-left: 25px"
                @click="handleAdd">新增</el-button>
            <el-button type="info" size="mini" icon="el-icon-edit" plain style="margin-left: 25px"
                @click="handleUpdate">编辑</el-button>
            <el-button type="primary" size="mini" icon="el-icon-tickets" plain style="margin-left: 25px"
                @click="showAppealDialog">成绩申诉</el-button>
            <el-button type="danger" size="mini" icon="el-icon-delete" plain style="margin-left: 25px"
                @click="handleDelete">删除</el-button>
            <el-button type="warning" size="mini" plain icon="el-icon-download" style="margin-left: 25px"
                @click="derive">导出</el-button>
        </div>

        <!-- 列表 -->
        <el-table size="small" :data="list" highlight-current-row v-loading="loading" border
            element-loading-text="拼命加载中" style="width: 96%; margin-top: 20px" @row-click="onRowClick"
            :span-method="arraySpanMethod" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55"></el-table-column>
            <el-table-column align="center" prop="onestep_substance" label="一级指标" width="100"></el-table-column>
            <el-table-column align="center" prop="twostep_substance" label="二级指标" width="280px"></el-table-column>
            <el-table-column align="center" prop="work_standingbook" label="工作台账" width="80"></el-table-column>
            <el-table-column align="center" prop="practicable" label="落实情况" width="80"></el-table-column>
            <el-table-column align="center" prop="score" label="分值" width="60"></el-table-column>
            <el-table-column align="center" prop="score_selfassessment" label="自评分" width="60"></el-table-column>
            <el-table-column align="center" prop="score_single" label="单项考评分" width="60"></el-table-column>
            <el-table-column align="center" prop="score_special" label="特殊加扣分"></el-table-column>
            <el-table-column align="center" prop="score_yearend" label="年终考评分"></el-table-column>
            <el-table-column align="center" prop="state_progress" label="进展状态"></el-table-column>
            <el-table-column align="center" prop="state_standingbook" label="台账申诉状态"></el-table-column>
            <el-table-column align="center" prop="state_plus" label="加扣分申诉状态" width="130"></el-table-column>
        </el-table>
        <!-- 添加、编辑表单弹窗 -->
        <el-dialog :title="title" :visible.sync="open" width="700px" append-to-body>
            <el-form ref="tableData" :model="tableData" :rules="rules" label-width="130px">
                <el-form-item label="二级指标" prop="twostep_substance">
                    <el-input v-model="tableData.twostep_substance" :disabled="title"></el-input>
                </el-form-item>
                <el-form-item label="工作台账" prop="work_standingbook">
                    <el-input v-model="tableData.work_standingbook" placeholder="请输入工作台账" />
                </el-form-item>
                <el-form-item label="落实情况" prop="practicable">
                    <el-input v-model="tableData.practicable" placeholder="请输入落实情况" />
                </el-form-item>
                <el-form-item label="分值" prop="score">
                    <el-input v-model="tableData.score" placeholder="请输入分值" />
                </el-form-item>
                <el-form-item label="自评分" prop="score_selfassessment">
                    <el-input v-model="tableData.score_selfassessment" placeholder="请输入自评分" />
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitForm">确 定</el-button>
                <el-button @click="cancel">取 消</el-button>
            </div>
        </el-dialog>

    </div>
</template>

<script>
import { save, addl, upda, delet, getyear } from "../../../api/zhenfu/bumen";

export default {
    data() {
        return {
            // tijiao: null, // 初始化为其他合适的值
            showAppealDialog: false,
            total: 0,
            towIndexOptions: [], // 填入默认值
            list: [],
            loading: false,
            yearNumber: "",
            work_standingbook: "",
            Working_status: "",
            statet: "",
            yearOptions: [],
            WorkingbookOptions: [],
            Working_statusOptions: [],
            statusOptions: [],
            tableData: {
                score_id: "",
                twostep_substance: "",
                work_standingbook: "",
                practicable: "",
                score: "",
                score_selfassessment: "",
            },
            selectedRows: [],
            open: false,
            title: "",
            rules: {
                work_standingbook: [
                    { required: true, message: "工作台账不能为空", trigger: "blur" },
                ],
                practicable: [
                    { required: true, message: "落实情况不能为空", trigger: "blur" },
                ],
                score: [{ required: true, message: "分值不能为空", trigger: "blur" }],
                score_selfassessment: [
                    { required: true, message: "自评分不能为空", trigger: "blur" },
                ],
            },
        };
    },
    created() {
        this.apply();
    },
    methods: {
        apply() {
            this.loading = true;
            save()
                .then((response) => {
                    console.log(response); // 查看返回的数据
                    if (response.result && response)  {
                        this.list = response.result; // 确保 list 为数组
                        console.log(this.list); // 检查 list 中的数据
                    } else {
                        this.$message.error("数据获取失败");
                    }
                    this.loading = false;
                })
                .catch((err) => {
                    console.log(err);
                    this.loading = false;
                });
        },
        handleAdd() {
            if (this.selectedRows.length === 1) {
                const selectedRow = this.selectedRows[0];
                if (selectedRow.work_standingbook || selectedRow.practicable) {
                    this.$message.warning("当前二级指标的工作台账和落实情况必须为空才能新增");
                    return;
                }
                this.open = true;
                this.title = "新增";
                this.tableData = {
                    twostep_id: selectedRow.twostep_id || "", // 确保有合适的值
                    twostep_substance: selectedRow.twostep_substance || "",
                    work_standingbook: "",
                    practicable: "",
                    score: "",
                    score_selfassessment: "",
                };
            } else {
                this.$message.warning("请选中一条记录进行新增");
            }
        },
        handleUpdate() {
            if (this.selectedRows.length === 1) {
                const selectedRow = this.selectedRows[0];
                if (selectedRow.work_standingbook && selectedRow.practicable) {
                    this.open = true;
                    this.title = "修改";
                    const score_id = selectedRow.score_id || null; // 如果为空字符串，置为 null
                    this.tableData = {
                        score_id: score_id,
                        twostep_substance: selectedRow.twostep_substance || "",
                        work_standingbook: selectedRow.work_standingbook || "",
                        practicable: selectedRow.practicable || "",
                        score: selectedRow.score || "",
                        score_selfassessment: selectedRow.score_selfassessment || "",
                    };

                } else {
                    this.$message.warning("修改操作只能在工作台账和落实情况有数据的情况下进行");
                }
            } else {
                this.$message.warning("请选中一条记录进行修改");
            }
        },
        handleSelectionChange(val) {
            this.selectedRows = val; // 确保 selectedRows 被正确设置
            console.log("Selected Rows:", this.selectedRows); // 调试输出
        },

        submitForm() {
            this.$refs.tableData.validate((valid) => {
                if (valid) {
                    const apiCall = this.title === "新增" ? addl : upda;
                    apiCall(this.tableData)
                        .then((response) => {
                            if (response.success && response) {
                                this.$message.success(this.title === "新增" ? "新增成功" : "修改成功");
                                this.open = false;
                                this.apply();
                            } else {
                                this.$message.error(this.title === "新增" ? "新增失败" : "修改失败");
                            }
                        })
                        .catch((err) => {
                            console.log('API调用失败:', err);
                            this.$message.error(this.title === "新增" ? "新增失败" : "修改失败");
                        });
                } else {
                    console.log("表单验证失败");
                    return false;
                }
            });
        }
        ,
        arraySpanMethod({ row, column, rowIndex, columnIndex }) {
            if (columnIndex === 1) {
                const onestep_substance = row.onestep_substance;
                const prevRow = this.list[rowIndex - 1];
                let rowSpan = 1;

                if (prevRow && prevRow.onestep_substance === onestep_substance) {
                    return [0, 0];
                }

                for (let i = rowIndex + 1; i < this.list.length; i++) {
                    if (this.list[i].onestep_substance === onestep_substance) {
                        rowSpan++;
                    } else {
                        break;
                    }
                }

                return [rowSpan, 1];
            } else {
                return [1, 1];
            }
        },
        handleDelete() {
            if (this.selectedRows.length) {
                this.$confirm("确定删除选中的数据吗？", "提示", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning",
                })
                    .then(() => {
                        const dtoBumen = this.selectedRows.map(row => ({ twostep_substance: row.twostep_substance }));
                        delet(dtoBumen)  // 传递 dtoBumen 对象
                            .then((res) => {
                                if (res.success) {
                                    this.$message.success("删除成功");
                                    this.apply();  // 重新加载数据
                                } else {
                                    this.$message.error(res.message || "删除失败");
                                }
                            })
                            .catch((err) => {
                                console.log(err);
                                this.$message.error("删除失败");
                            });
                    })
                    .catch(() => {
                        this.$message.info("已取消删除");
                    });
            } else {
                this.$message.warning("请先选择要删除的行");
            }
        },

        derive() {
            this.download(
                "traget/book/export",
                {
                    ...this.queryParams,
                },
                `book_${new Date().getTime()}.xlsx`
            );
        },
        onRowClick(row) {
            row.selected = !row.selected;
        },
        handleCurrentChange(val) {
            this.list.pageNum = val;
            this.apply();
        },
        cancel() {
            this.open = false;
        },
    },
};
</script>
<style scoped>
.box {
    width: 100%;
    height: 100%;
    margin-left: 30px;
    /* margin-top: 20px; */
}

.an {
    margin-top: 20px;
}
</style>